﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight.InputCtrl
{
    public class CustomValidator: ValidatorBase
    {

        public event DependencyPropertyChangedEventHandler CustomValidate;

        private static readonly DependencyProperty TriggerValidateProperty =
            DependencyProperty.Register("TriggerValidate", typeof(bool), typeof(CustomValidator),
              new PropertyMetadata(new PropertyChangedCallback(TriggerValidateChange)));

        public static readonly DependencyProperty ExternalResultProperty =
            DependencyProperty.Register("ExternalResult", typeof(bool), typeof(CustomValidator),new PropertyMetadata(false));


        private static void TriggerValidateChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            (obj as CustomValidator).OnTriggerPropertyChanged(e);
        }

        private void OnTriggerPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            if (CustomValidate == null)
                return;
            CustomValidate(this,e);
        }


        public override bool Validate()
        {
            base.IsValidResult = true;
            FrameworkElement _elemValidate = base.ElementValidator;
            if (_elemValidate != null && Enabled)
            {
                string value = ValidatorCommon.GetValueText(_elemValidate, base.PropertyToValidate);
                if (!String.IsNullOrEmpty(value))
                {
                    bool valuechange = (bool)this.GetValue(CustomValidator.TriggerValidateProperty);
                    this.SetValue(CustomValidator.TriggerValidateProperty, !valuechange);
                    base.IsValidResult = (bool)this.GetValue(CustomValidator.ExternalResultProperty);
                }
            }
            return base.IsValidResult;
        }
    }
}
